#include "dialog.h"
#include "ui_dialog.h"
#include <QtCore/QCoreApplication>

Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
    ui->setupUi(this);
    UdpSofd = new QUdpSocket(this);// 创建UDP的套接字
    TcpSofd= new QTcpSocket(this);// 创建TCP的套接字
    fliesocket =new QTcpSocket(this);//创建TCP的CJson套接字
    // 绑定套接字
    if (!UdpSofd->bind(QHostAddress::Any, 5414))
    {
        qWarning() << "Failed to bind UDP socket:" << UdpSofd->errorString();
    }
    else
    {
        qDebug() << "UDP socket successfully bound to port 5414";
    }
    // 点击发广播（SofdSend）
    connect(ui->pushButton_SofdSend, &QPushButton::clicked, this, &Dialog::SofdSend);
    // 连接接收数据的信号槽
    connect(UdpSofd, &QUdpSocket::readyRead, this, &Dialog::GetFirstText);
    // 连接 TCP 连接信号槽
    connect(ui->pushButton,&QPushButton::clicked,this,&Dialog::ConnectToServer);
    // 接收到服务器的消息
    connect(TcpSofd, &QTcpSocket::readyRead, this, &Dialog::ReadServerResponse);
    //下发心跳包
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this,SLOT(heartTimer()));
    timer->start(1000); // 1000毫秒为间隔

}

Dialog::~Dialog()
{
    delete ui;
    delete UdpSofd;// 关闭的套接字
    delete TcpSofd;//关闭TCP的套接字
    delete fliesocket;//关闭TCP的点表
}

// 发广播
void Dialog::SofdSend()
{
    // 设置广播地址
    QHostAddress BroadcastAddress("192.168.51.255");
    // 构造广播消息
    QString message("WhoIsNaughtyDragon");
    QByteArray BroadcastMessage = message.toUtf8();
    // 设置广播端口号
    qint16 BroadcastPort = 5414;
    // 发送广播
    UdpSofd->writeDatagram(BroadcastMessage, BroadcastAddress, BroadcastPort);
    qDebug() << "Broadcast message sent!";
}
// 接收消息并处理
void Dialog::GetFirstText()
{
    // 检查是否有待处理的数据
    while (UdpSofd->hasPendingDatagrams())
    {
        QByteArray buffer;
        buffer.resize(UdpSofd->pendingDatagramSize());
        //获取服务器的IP和端口号
        QHostAddress sender;
        quint16 senderPort;
        // 读取数据
        int bytesRead = UdpSofd->readDatagram(buffer.data(), buffer.size(), &sender, &senderPort);
        if (bytesRead > 0)
        {
            //用临时全局变量来接收每一个服务器的IP Port
            IP=sender;
            Port=senderPort;
            //展示在UI上
            QString ShowIP = sender.toString();
            ui->textBrowser_Show->append(ShowIP);
            QString text(buffer);
            qDebug() << "Received message: " << text;

            // 判断是否是自己的设备
            if (text == "IAmNaughtyDragon")
            {
                qDebug() << "真棒"<<" "<<sender<<" "<< senderPort;
            }
            else
                qDebug()<<"失败";
        }
    }
}
//TCP连接
void Dialog::ConnectToServer()
{
    //连接服务器
    TcpSofd->connectToHost(IP,Port);
    //连接成功检测
    if(TcpSofd->waitForConnected(3000))
    {
        qDebug()<<"Successful connect to server";
        ui->textBrowser_Show->append("Successful connect to server");
        //给VMware下发点表
        json["type"] = 1;//将json格式 "type" 字段的值设置为 1。
        // 创建JSON文档
        QJsonDocument jsonDoc(json);
        // 将JSON文档转换为字节数组
        QByteArray jsonData = jsonDoc.toJson();
        // 发送JSON数据
        TcpSofd->write(jsonData);
        SendFile();
    }
    else
    {
        qDebug()<<"critical";
        ui->textBrowser_Show->append("connect failure ");
    }
}
//心跳包显示
void Dialog::ReadServerResponse()
{
    QByteArray response = TcpSofd->readAll();
    QString text = QString::fromUtf8(response);
    if(text == "living")
    {
        qDebug()<<"precess living";
    }
}

//下发点表
void Dialog::SendFile()
{
    fliesocket->connectToHost(IP,1333);
    QFile readFile(":/new/prefix1/node.json");
    readFile.open(QIODevice::ReadOnly);//以只读方式读取文件
    QByteArray file;  //用于存储即将读取的文件内容。
    qint64 totalSize = readFile.size();//获取到文件的总大小
//    qDebug()<<totalSize;
    file = readFile.read(totalSize);//读取文件的全部内容
//    qDebug()<<file;
    fliesocket->write(file);//向设备发送文件
    this->close();
    h =new HomePage;
    qDebug()<<"********************************";
    h->show();
}
//下发心跳包
void Dialog::heartTimer()
{
    // 添加其他键值对
    json["type"] = 3;
    // 创建JSON文档
    QJsonDocument jsonDoc(json);
    // 将JSON文档转换为字节数组
    QByteArray jsonData = jsonDoc.toJson();

    // 发送JSON数据
    TcpSofd->write(jsonData);

    // 等待数据发送完毕
    if (TcpSofd->waitForBytesWritten())
    {
        qDebug() << "JSON data sent successfully1";
    } else
    {
        qDebug() << "Failed to send JSON data";
    }
}


